using System.Drawing;

namespace Sherwood.Imaging.Providers
{
    public class StringRectangleProvider : ISizeProvider
    {
        public IStringProvider StringProvider { get; set; }
        public IFontProvider FontProvider { get; set; }
        public ISizeProvider BoundariesProvider { get; set; }

        public StringRectangleProvider(IStringProvider stringProvider, IFontProvider fontProvider) : this(stringProvider, fontProvider, null)
        {
        }

        public StringRectangleProvider(IStringProvider stringProvider, IFontProvider fontProvider, ISizeProvider boundariesProvider)
        {
            StringProvider = stringProvider;
            FontProvider = fontProvider;
            BoundariesProvider = boundariesProvider;
        }

        public SizeF GetSize(Image image)
        {
            using (var graphics = Graphics.FromImage(image))
            {
                SizeF? boundaries = BoundariesProvider == null
                                        ? (SizeF?) null
                                        : BoundariesProvider.GetSize(image);
                var text = StringProvider.GetString();
                var font = FontProvider.GetFont();
                return boundaries != null
                           ? graphics.MeasureString(text, font, boundaries.Value)
                           : graphics.MeasureString(text, font);
            }
        }
    }
}